package com.zjq.springsocial.renren.android;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import net.simonvt.menudrawer.MenuDrawer;
import net.simonvt.menudrawer.Position;

import org.springframework.social.connect.Connection;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.zjq.springsocial.renren.android.ui.RenrenMainActivity;
import com.zjq.springsocial.renren.api.Renren;

/**
 * 
 *<P>人人网开放平台API接口实现，异步的抽象activity</P> 
 *<p>使用了开源的Action Bar项目{@link http://actionbarsherlock.com}和开源的项目menudrawer {@link https://github.com/SimonVT/android-menudrawer}
 *
 * @author zhongjingquan
 * @version 0.0.1-SNAPSHOT 2013-7-18下午5:25:15
 */
public abstract class RenrenAbstractAsyncActivity extends SherlockFragmentActivity implements RenrenAsyncListener{
	
	protected static final String TAG = RenrenAbstractAsyncActivity.class.getSimpleName();
	
	protected static final String LAST_ACTIVITY_PREFERENCE = "renren_pref_last_activity";
	
	protected boolean mFirstLaunch = false;//是否首次启动的activity
	protected boolean mShouldFinish;
	
	//提供接口基类
	protected Renren renrenApi;
	
	//菜单对应的ID
	protected static final int MAIN_ACTIVITY = 0;
	
	//加载进度对话框
	private ProgressDialog progressDialog;

	private boolean destroyed = false;

	//菜单的绘制对象 MenuDrawer 是开源项目 menudrawer 提供的
	protected MenuDrawer mMenuDrawer;
	//菜单适配器 
    protected MenuAdapter mAdapter;
    protected ListView mList;    
    private ListView mListView;
    protected List<MenuDrawerItem> mMenuItems = new ArrayList<MenuDrawerItem>();
    
    //标识是否平板设备
    private boolean mIsXLargeDevice;
	
	@Override
	public RenrenAppliction getApplicationContext(){
		return (RenrenAppliction) super.getApplicationContext();
	}
	
	@Override
    protected void onCreate(Bundle inState) {
		super.onCreate(inState);
		//判断是否平板
        if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == 4)
            mIsXLargeDevice = true;
        
        //添加主页板
        mMenuItems.add(new MainMenuItem());
        
        //获取提供的基类API接口对象
        Connection<Renren> conRenren = getApplicationContext().getConnectionRepository().findPrimaryConnection(Renren.class);
        if(conRenren != null)
        	renrenApi = conRenren.getApi();
	}
	
	//延迟跳转
	protected void startActivityWithDelay(final Intent i) {
        if (mIsXLargeDevice && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        	//是平板，不需要延迟
            startActivity(i);
        } else {
        	//是第一个运行的activity不用延迟
            if (mFirstLaunch) {
                startActivity(i);
                return;
            }
            //否则延迟
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    startActivity(i);
                }
            }, 400);
        }
    }
	
	@Override
    protected void onPause() {
        super.onPause();
        if (mShouldFinish) {
            overridePendingTransition(0, 0);
            finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshUI();
    }

    private void refreshUI(){
        if (mMenuDrawer != null) {
            updateMenuDrawer();
        }
    }
	
	/**
	 * 用于设备横向切换的时候，不用重新实例新的activity
	 */
    public void onConfigurationChanged(Configuration newConfig) {
        if (mIsXLargeDevice) {//如果是平板
            if (mMenuDrawer != null) {
                View content = mMenuDrawer.getContentContainer().getChildAt(0);
                if (content != null) {
                    mMenuDrawer.getContentContainer().removeView(content);
                    mMenuDrawer = attachMenuDrawer();
                    mMenuDrawer.setContentView(content);
                    initMenuDrawer();
                }
            }
        }
        super.onConfigurationChanged(newConfig);
    }
	
    /**
     * 菜单单击事件
     */
	public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            if (mMenuDrawer != null) {
                mMenuDrawer.toggleMenu();
                return true;
            }
//        } else if (item.getItemId() == R.id.menu_settings) {
//            Intent i = new Intent(this, PreferencesActivity.class);
//            startActivityForResult(i, SETTINGS_REQUEST);
//        } else if (item.getItemId() == R.id.menu_signout) {
//            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
//            dialogBuilder.setTitle(getResources().getText(R.string.sign_out));
//            dialogBuilder.setMessage(getString(R.string.sign_out_confirm));
//            dialogBuilder.setPositiveButton(R.string.sign_out,
//                    new DialogInterface.OnClickListener() {
//                        public void onClick(DialogInterface dialog,
//                                            int whichButton) {
//                            WordPress.signOut(WPActionBarActivity.this);
//                            refreshUI();
//                        }
//                    });
//            dialogBuilder.setNegativeButton(R.string.cancel,
//                    new DialogInterface.OnClickListener() {
//                        public void onClick(DialogInterface dialog,
//                                            int whichButton) {
//                            // Just close the window.
//                        }
//                    });
//            dialogBuilder.setCancelable(true);
//            if (!isFinishing())
//                dialogBuilder.create().show();
        }
        return super.onOptionsItemSelected(item);
    }
	
	//创建一个菜单绘制对象MenuDrawer,将对应的内容视图id关联
	protected void createMenuDrawer(int contentViewID) {
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        mMenuDrawer = attachMenuDrawer();
        mMenuDrawer.setContentView(contentViewID);
        
        initMenuDrawer();
	}
	
	//创建一个菜单绘制对象MenuDrawer,将对应的内容视图对象关联
    protected void createMenuDrawer(View contentView) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        
        mMenuDrawer = attachMenuDrawer();
        mMenuDrawer.setContentView(contentView);

        initMenuDrawer();
    }
	
	//设置菜单绘制对象
	private MenuDrawer attachMenuDrawer(){
		MenuDrawer menuDrawer = null;
		if (mIsXLargeDevice) {
            //判断设备是否平板横切方向
            if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                menuDrawer = MenuDrawer.attach(this, MenuDrawer.Type.STATIC, Position.LEFT);
                getSupportActionBar().setDisplayHomeAsUpEnabled(false);
            } else {
                menuDrawer = MenuDrawer.attach(this, MenuDrawer.Type.OVERLAY);
                getSupportActionBar().setDisplayHomeAsUpEnabled(true);
                menuDrawer.setDrawerIndicatorEnabled(true);
            }
        } else {
            menuDrawer = MenuDrawer.attach(this, MenuDrawer.Type.OVERLAY);
            menuDrawer.setDrawerIndicatorEnabled(true);
        }
        int shadowSizeInPixels = getResources().getDimensionPixelSize(R.dimen.menu_shadow_width);
        menuDrawer.setDropShadowSize(shadowSizeInPixels);
        menuDrawer.setDropShadowColor(getResources().getColor(R.color.md__shadowColor));
        menuDrawer.setSlideDrawable(R.drawable.ic_drawer);
        return menuDrawer;
	}
	
	//初始化创建ListView菜单
    private void initMenuDrawer() {
    	mListView = new ListView(this);
    	mListView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		mListView.setDivider(null);
	    mListView.setDividerHeight(0);
	    mListView.setCacheColorHint(android.R.color.transparent);
	    mAdapter = new MenuAdapter(this);
	    
	    mListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // account for header views
                int menuPosition = position - mListView.getHeaderViewsCount();
                // bail if the adjusted position is out of bounds for the adapter
                if (menuPosition < 0 || menuPosition >= mAdapter.getCount())
                    return;
                MenuDrawerItem item = mAdapter.getItem(menuPosition);
                // if the item has an id, remember it for launch
                if (item.hasItemId()){
                    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(RenrenAbstractAsyncActivity.this);
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putInt(LAST_ACTIVITY_PREFERENCE, item.getItemId());
                    editor.commit();
                }
                // only perform selection if the item isn't already selected
                if (!item.isSelected())
                    item.selectItem();
                // save the last activity preference
                // close the menu drawer
                mMenuDrawer.closeMenu();
                // if we have an intent, start the new activity
            }
        });
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {
                mMenuDrawer.invalidate();
            }
        });
        
        mMenuDrawer.setMenuView(mListView);
        mListView.setAdapter(mAdapter);
        updateMenuDrawer();
	    
    }

    //更新菜单绘制对象
    protected void updateMenuDrawer() {
        mAdapter.clear();

        Iterator<MenuDrawerItem> availableItems = mMenuItems.iterator();
        while(availableItems.hasNext()){
            MenuDrawerItem item = availableItems.next();
            if (item.isVisible()) {
                mAdapter.add(item);
            }
        }
        
        mAdapter.notifyDataSetChanged();

    }
	
	//实现一个菜单数据类型的适配器，加载菜单
	public static class MenuAdapter extends ArrayAdapter<MenuDrawerItem> {
		MenuAdapter(Context context) {
            super(context, R.layout.menu_drawer_row, R.id.menu_row_title, new ArrayList<MenuDrawerItem>());
        }
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = super.getView(position, convertView, parent);
			
			//获取菜单项
			MenuDrawerItem item = getItem(position);
			
			TextView titleTextView = (TextView) view.findViewById(R.id.menu_row_title);
            titleTextView.setText(item.getTitleRes());

            ImageView iconImageView = (ImageView) view.findViewById(R.id.menu_row_icon);
            iconImageView.setImageResource(item.getIconRes());
			
            //Hide the badge always
            view.findViewById(R.id.menu_row_badge).setVisibility(View.GONE);
            
            if (item.isSelected()) {
                int bottom = view.getPaddingBottom();
                int top = view.getPaddingTop();
                int right = view.getPaddingRight();
                int left = view.getPaddingLeft();
                view.setBackgroundResource(R.drawable.menu_drawer_selected);
                view.setPadding(left, top, right, bottom);
            } else {
                view.setBackgroundResource(R.drawable.md_list_selector);
            }
            item.configureView(view);
			return view;
		}
	}

	/**
	 * 当用户点击返回按钮时回调
     */
    @Override
    public void onBackPressed() {
        if (mMenuDrawer != null) {
            final int drawerState = mMenuDrawer.getDrawerState();
            if (drawerState == MenuDrawer.STATE_OPEN || drawerState == MenuDrawer.STATE_OPENING) {
                mMenuDrawer.closeMenu();
                return;
            }
        }

        super.onBackPressed();
    }
	
    //主屏幕菜单
    public class MainMenuItem extends MenuDrawerItem{

		MainMenuItem() {
			super(MAIN_ACTIVITY,R.string.posts,R.drawable.dashboard_icon_posts);
		}
		
		@Override
		public Boolean isSelected() {
			return RenrenAbstractAsyncActivity.this instanceof RenrenMainActivity;
		}

		@Override
		public void onSelectItem() {
			if(!(RenrenAbstractAsyncActivity.this instanceof RenrenMainActivity))
				mShouldFinish = true;
			Intent intent = new Intent(RenrenAbstractAsyncActivity.this,RenrenMainActivity.class);
			startActivityWithDelay(intent);
		}
    	
    }
    
	@Override
	protected void onDestroy() {
		super.onDestroy();
		this.destroyed = true;
	}
	
	public void showLoadingProgressDialog() {
		String loadStr = getString(R.string.load_data);
		this.showProgressDialog(loadStr);
	}

	public void showProgressDialog(CharSequence message) {
		if (this.progressDialog == null) {
			this.progressDialog = new ProgressDialog(this);
			this.progressDialog.setIndeterminate(true);
		}

		this.progressDialog.setMessage(message);
		this.progressDialog.show();
	}

	public void dismissProgressDialog() {
		if (this.progressDialog != null && !this.destroyed) {
			this.progressDialog.dismiss();
		}
	}
}
